package com.atguigu.lease.web.admin.custom.interceptor;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author：yyj
 * @Package：com.atguigu.lease.web.admin.custom.interceptor
 * @Project：project01
 * @name：AuthenticationInterceptor
 * @Date：2024/11/21 14:45
 * @Filename：AuthenticationInterceptor
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String accessToken = request.getHeader("access_token");
        Claims claims = JwtUtil.parseToken(accessToken);

        Long userId = claims.get("userId", Long.class);
        String username = claims.get("username", String.class);

        LoginUserContext.setLoginUser(new LoginUser(userId,username));

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserContext.clear();
    }
}
